package com.hsq.androidproject.utils;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.hsq.androidproject.ui.fragment.FindFragment;
import com.hsq.androidproject.ui.fragment.RecommendFragment;
import com.hsq.androidproject.ui.fragment.WatchingFragment;

import java.util.ArrayList;


/**
 * Created by Administrator on 2017/3/1.
 */

public class FragmentUtil {
    private static FragmentUtil fragmentUtil;
    private final FragmentManager fm;
    private int mGroupId;
    private ArrayList<Fragment> fragments = new ArrayList<>();


    public FragmentUtil(FragmentActivity activity, int groupId) {
        fm = activity.getSupportFragmentManager();
        this.mGroupId = groupId;
        initFragment();
    }

    public static FragmentUtil getIntance(FragmentActivity activity, int groupId) {
        if (fragmentUtil == null) {
            fragmentUtil = new FragmentUtil(activity, groupId);
        }
        return fragmentUtil;
    }

    private void initFragment() {
        //初始化Fragment
        fragments.add(new RecommendFragment());
        fragments.add(new FindFragment());
        fragments.add(new WatchingFragment());

        //replace
        FragmentTransaction ft = fm.beginTransaction();
        for (Fragment fragment : fragments) {
            ft.add(mGroupId, fragment);
        }
        ft.commitAllowingStateLoss();
    }


    /**
     * 显示的Fragment
     *
     * @param position 位置
     */
    public void showFragment(int position) {
        hideFragment();
        FragmentTransaction ft = fm.beginTransaction();
        ft.show(fragments.get(position));
        ft.commitAllowingStateLoss();
    }


    /**
     * 隐藏全部Fragment
     * 在调用showFragment 方法的时候 先全部隐藏那个
     */
    public void hideFragment() {

        FragmentTransaction ft = fm.beginTransaction();
        for (Fragment fragment : fragments) {
            ft.hide(fragment);
        }
        ft.commitAllowingStateLoss();
    }
}
